package com.wwdeng.print.app.meituan

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.sankuai.hardware.mthwsrvmgrsdk.IPrintCallback
import com.sankuai.hardware.mthwsrvmgrsdk.MTHardwareCenter
import com.wwdeng.print.app.BaseAct
import com.wwdeng.print.app.R
import com.wwdeng.print.app.databinding.ActSdkMeituanBinding
import com.wwdeng.print.app.meituan.MeiTuanPrintHelper.formatPrintHandOver
import com.wwdeng.print.app.meituan.MeiTuanPrintHelper.formatPrintInvoice
import com.wwdeng.print.app.meituan.MeiTuanPrintHelper.formatPrintPreSettlementOrder
import com.wwdeng.print.app.meituan.MeiTuanPrintHelper.formatPrintSettlementOrder
import com.wwdeng.print.app.printer.EscPosUtils
import com.wwdeng.print.app.printer.TestPrintData
import org.json.JSONObject

/**
 * PrintTestDemo
 * @Author：wwdeng
 * @CreateTime：2025/4/1 00:33
 * <pre>
 *      美团内置打印机 SDK
 * </pre>
 */
class MeiTuanSdkAct: BaseAct() {
    private val TAG = "MeiTuan"
    lateinit var binding: ActSdkMeituanBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActSdkMeituanBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initMeiTuanSdk()
        //打印预结单
        binding.btnPrint.setOnClickListener {
            //模拟预结订单信息
            val preOrderData = TestPrintData.getPreOrderData()

            val list: MutableList<ByteArray> = ArrayList()
            list.formatPrintPreSettlementOrder(preOrderData)
            //切纸
            list.add(EscPosUtils.cutPaper())

            val printDate = EscPosUtils.concatBytes(*list.toTypedArray())
            val result = onStartPrintAction(printDate)
            if (result < 0) {
                showToast("打印失败")
            }
        }

        //打印结账单
        binding.btnPrint2.setOnClickListener {
            //模拟结账单信息
            val settlementOrderData = TestPrintData.getSettlementOrderData()

            val list: MutableList<ByteArray> = ArrayList()
            list.formatPrintSettlementOrder(settlementOrderData)
            //切纸
            list.add(EscPosUtils.cutPaper())

            val printDate = EscPosUtils.concatBytes(*list.toTypedArray())
            val result = onStartPrintAction(printDate)
            if (result < 0) {
                showToast("打印失败")
            }
        }

        //打印发票
        binding.btnPrint3.setOnClickListener {
            //模拟发票信息
            val invoiceData = TestPrintData.getInvoiceData()

            val list: MutableList<ByteArray> = ArrayList()
            list.formatPrintInvoice(invoiceData)
            //切纸
            list.add(EscPosUtils.cutPaper())

            val printDate = EscPosUtils.concatBytes(*list.toTypedArray())
            val result = onStartPrintAction(printDate)
            if (result < 0) {
                showToast("打印失败")
            }
        }
        //打印交班单
        binding.btnPrint4.setOnClickListener {
            //模拟交班单信息
            val handOverData = JSONObject()
            handOverData.put("logoResId", R.mipmap.test_logo)

            val list: MutableList<ByteArray> = ArrayList()
            list.formatPrintHandOver(handOverData)
            //切纸
            list.add(EscPosUtils.cutPaper())

            val printDate = EscPosUtils.concatBytes(*list.toTypedArray())
            val result = onStartPrintAction(printDate)
            if (result < 0) {
                showToast("打印失败")
            }
        }
    }

    /**
     * 在APP启动或者主页面onCreate()时调用init(Context context)接口，用于初始化内部设备及绑定硬件服务
     */
    @SuppressLint("SetTextI18n")
    private fun initMeiTuanSdk(){
        val initResult = MTHardwareCenter.get().init(this) { result -> // 初始化结果 result: true 成功，false 失败
            Log.e(TAG, "meituan sdk init async result: $result")
            binding.tvInitResult.text = "MeiTuan Sdk 初始化异步结果: $result"
            showPrintInfo()
        }
        Log.e(TAG, "meituan sdk init sync result: $initResult")
        binding.tvInitResult.text = "MeiTuan Sdk 初始化同步结果: $initResult"
    }

    @SuppressLint("SetTextI18n")
    private fun showPrintInfo(){
        val mtHardwareCenter = MTHardwareCenter.get()
        binding.tvPrinterSupported.text = "是否支持内置打印机：${mtHardwareCenter.isPrinterSupported}"
        binding.tvPrinterConnected.text = "内置打印机是否连接：${mtHardwareCenter.isPrinterConnected}"

        binding.tvPrinterConnectionType.text = "内置打印机连接类型：${
            when(mtHardwareCenter.printerConnectionType){
                0 -> "未知"
                1 -> "串口打印机"
                2 -> "USB打印机"
                else -> "获取失败"
            }
        }"

        binding.tvPrinterPaperType.text = "打印纸类型：${
            when(mtHardwareCenter.printerPaperType){
                0 -> "未知"
                1 -> "58mm"
                2 ->  "80mm"
                else -> "获取失败"
            }
        }"

        binding.tvPrintedLength.text = "打印机历史累计打印长度：${
            when(mtHardwareCenter.printedLength){
                -1 ->  "获取失败"
                else ->  "${mtHardwareCenter.printedLength}mm"
            }
        }"

        binding.tvPrinterCutPaperCount.text = "打印总次数：${
            when(mtHardwareCenter.printerCutPaperTimes){
                -1 -> "获取失败"
                else -> "${mtHardwareCenter.printerCutPaperTimes}"
            }
        }"

        binding.tvPrinterFirmwareVersion.text = "打印机固件版本号：${
            when(mtHardwareCenter.printerFirmwareVersion){
                "",null -> "获取失败"
                else -> mtHardwareCenter.printerFirmwareVersion
            }
        }"

        binding.tvPrinterHardwareVersion.text = "打印机硬件版本号：${
            when(mtHardwareCenter.printerHardwareVersion){
                "",null -> "获取失败"
                else -> mtHardwareCenter.printerHardwareVersion
            }
        }"

        binding.tvPrinterBrandName.text = "打印机品牌：${
            when(mtHardwareCenter.printerBrandName){
                "",null -> "获取失败"
                else -> mtHardwareCenter.printerBrandName
            }
        }"

        binding.tvPrinterStatus.text = "打印机运行状态：未知"
        if (mtHardwareCenter.isPrinterSupported && mtHardwareCenter.isPrinterConnected){
            binding.tvPrinterStatus.text = "打印机运行状态：${
                when(mtHardwareCenter.printerStatus){
                    -1 -> "电源错误"
                    -2 -> "打印机不存在"
                    -3 -> "打印机未连接"
                    -4 -> "正在升级固件"
                    -5 -> "切刀错误"
                    -6 -> "仓盖已打开"
                    -7 -> "缺纸"
                    -8 -> "过热"
                    -9 -> "重试超时"
                    -10 -> "未知错误"
                    else -> "正常"
                }
            }"
        }
    }

    /**
     * 打印
     */
    private fun onStartPrintAction(printData: ByteArray): Int{
        if (!MTHardwareCenter.get().isPrinterSupported){
            showToast("该设备不支持内置打印机")
            return -1
        }
        if (!MTHardwareCenter.get().isPrinterConnected){
            showToast("内置打印机未连接")
            return -1
        }
        if (MTHardwareCenter.get().printerStatus != 0){
            showToast("打印机运行状态不正确: ${MTHardwareCenter.get().printerStatus}")
            return -1
        }
        return MTHardwareCenter.get().print(printData,object : IPrintCallback.Stub() {
            override fun onSuccess() {
                Log.e(TAG,"meituan sdk print success")
                showToast("打印成功")
            }

            override fun onFailure(code: Int, msg: String?) {
                Log.e(TAG,"meituan sdk print failure, code: $code, msg: $msg")
                showToast("打印失败，错误码:$code,错误原因:$msg")
            }
        })
    }

    private fun showToast(msg: String){
        Toast.makeText(this,msg,Toast.LENGTH_SHORT).show()
    }

    /**
     * 在APP销毁或者主页面onDestroy()时调用release()接口，用于释放内部设备资源及解绑硬件服务
     */
    private fun releaseMeiTuanSdk(){
        MTHardwareCenter.get().release()
    }

    override fun onDestroy() {
        super.onDestroy()
        releaseMeiTuanSdk()
    }
}